---
--类名: CaptainController.lua
--创建日期: 2018-9-22
--创建人: 宋建邦
--功能描述: 船长室控制器
--修改内容:
local CaptainView = import(".CaptainView")
local MessageView = import(".CaptainMessageView")
local CaptainMyCollectsView = import(".CaptainMyCollectsView")
local CaptainModel = import(".CaptainModel")
local CaptainTips = import(".CaptainTips")
local CaptainObtainView = import(".CaptainObtainView")

local fileName = string.getModeName(...)
local CaptainController = class(fileName, app.mvc.ControllerBase)

function CaptainController:ctor(params)
    self.super.ctor(self, params)
end

function CaptainController:init()
    self:initCollectors()
    self:initLocations()
    self:initTalks()
    self:addSessionListener()
end

function CaptainController:addSessionListener()
    app.session:on("pb_captainRoom.S2C_NewCollectorNotice",function(ret)
        if self.hCollectors[ret.id] then
            if self.myModel then
                self.myModel:addLocalCollect(ret.id)
            end
            UIHandler:showThirdLevelTips( { remindId = Constant.FUNC_TYPE_CAPTAIN_ROOM, params = self.hCollectors[ret.id] } )
        end
    end)

    app.session:on("pb_captainRoom.S2C_NewCaptainRoomMessage",function(ret)
        -- print("send message new capta messafge................")
        app:sendMsg("IMModel", "addSystemMsg", L("captain_new_message"))
    end)
end

function CaptainController:setFilter(filters,params)
    local popui = UIHandler:getPopupUi()
    local renderTexture = self._renderTexture
    if filters then
        if not renderTexture then
            renderTexture = cc.RenderTexture:create(display.width,display.height)
            renderTexture:retain()
            self._renderTexture = renderTexture
        end
        
        local sprite = self._filterSprite
        if sprite then
            sprite:removeFromParent()
            self._filterSprite = nil
        end

        sprite = display.newFilteredSprite(renderTexture:getSprite():getTexture(), filters, params)
        self._filterSprite = sprite
        popui:addChild(sprite)
        sprite:setPosition(display.cx,display.cy)
        sprite:setScaleY(-1)
        
        self.capView:setVisible(false)
    else        
        if renderTexture then
            renderTexture:release()
            self._renderTexture = nil

            local sprite = self._filterSprite
            if sprite:getParent() then
                sprite:removeFromParent()
                self._filterSprite = nil
            end
        end
        self.capView:setVisible(true)
    end
end

function CaptainController:update(dt)
    local renderTexture = self._renderTexture
    if renderTexture then
        self.capView:setVisible(true)
        renderTexture:begin()
        self.capView:visit()
        -- if self:getScreenLayer() then
        --     self:getScreenLayer():visit()
        -- end
        renderTexture:endToLua()
        self.capView:setVisible(false)
    end
end

function CaptainController:getTouchMask()
    if not cc.isDead(self.mask) then
        return self.mask
    end
    local l = ccui.Layout:create()
    -- l:setLayoutType(ccui.LayoutType.VERTICAL)
    l:setContentSize(cc.size(display.width, display.height))
    l:setBackGroundColor(cc.c3b(78, 78, 78))
    l:setTouchEnabled(true)
    l:setLocalZOrder(999)
    l:addClickEventListener(function(sender)
        self:hideCaptainTips(true)
    end)

    self.mask = l
    -- self:addChild(l)
    UIHandler:addPopupUi(l, "captaintipsmasklayer")
    return self.mask
end

function CaptainController:transTime(s)
    local off = app.session:getServerTime() - s
    local h = off/3600
    if h > 0 and h < 1 then
        return string.format(L("lua_code_text_27"), tostring(math.ceil(off/60)))
    elseif h >= 1 and h < 24 then
        return string.format(L("lua_code_text_267"), tostring(math.floor(h)))
    else
        return string.format(L("lua_code_text_220"), tostring(math.floor(h/24)))
    end
    return tostring(off)
end

function CaptainController:userBaseDataFromWho(w)
    return {
        mountId = 0,
        hairID = w.HairID,
        faceID = w.FaceID,
        hairColorID = w.HairColorID,
        raceID = w.RaceID,
        gender = w.Gender,
        classID = w.ClassID,
        fashionIDs = w.FashionIDs,
        Name = w.Name,
        GuildName = w.GuildName,
        TitleID = w.TitleID
    }
end

function CaptainController:openRandCaptainView()
    self:openCaptainView()

    app.session:request("pb_captainRoom.C2S_VisitRandomCaptainRoom",{},function(msg)
        if msg.ok and cc.isDead(self.capView) == false then
            local capid = msg.data.AgentData.OwnerInfo.Uid 

            self.capModel = CaptainModel.new(capid)
            self.capView:setCaptainID(capid)

            self.capModel:read(msg.data)
            EM:notify(CaptainController.RoomDataChange)
        end
    end)
end

function CaptainController:openCaptainView(uid)
    app:sendMsg("IMRoomController", "hideView") 
    if self.capView == nil or cc.isDead(self.capView) then
        self.capView = CaptainView.new(app.mvc.VIEWTYPE_BLUR)
        self:setParentType("systemUI") 
        self:addChild(self.capView)
        self:setParentType("popupUI") 
        self.capView:show()
        self.capView:enterAction()
    end

    if uid ~= nil then
        self.capModel = CaptainModel.new(uid)
        self.capView:setCaptainID(uid)
        self:reqRoomData(uid)
    end    
    -- self.capView:schedule(handler(self, self.update), 0)
    self:clearUpdateEvent()
    local eventDispatcher = cc.Director:getInstance():getEventDispatcher()
    self.customListenerMw = cc.EventListenerCustom:create("director_after_update",
                                handler(self, self.update))
    eventDispatcher:addEventListenerWithFixedPriority(self.customListenerMw, 1)
end

function CaptainController:closeCaptainView()
    if self.capView then
        self:setParentType("systemUI") 
        self:removeChild(self.capView)
        self:setParentType("popupUI") 
        self.capView = nil
    end

    self:clearUpdateEvent()
end

function CaptainController:clearUpdateEvent()
    if self.customListenerMw then
        local eventDispatcher = cc.Director:getInstance():getEventDispatcher()
        eventDispatcher:removeEventListener(self.customListenerMw)
        self.customListenerMw = nil
    end
end

function CaptainController:openCollectView(m)
    if self.collectView then
        self:closeCollectView()
    end

    self.collectView = CaptainMyCollectsView.new(m)

    self:addChild(self.collectView)
    self.collectView:show()

    self.collectView:refresh(m)
end

function CaptainController:closeCollectView()
    if self.collectView then
        self:removeChild(self.collectView)
        self.collectView = nil
    end
end

function CaptainController:openMessageView(m)
    if cc.isDead(self.msgView) then
        self.msgView = MessageView.new()
    end

    self:addChild(self.msgView)
    self.msgView:show()

    self.msgView:refresh(m)
    self:reqMessage(m:getCaptainID())
end

function CaptainController:closeMessageView()
    if not cc.isDead(self.msgView) then
        self:removeChild(self.msgView)
        self.msgView = nil
    end
end

function CaptainController:tipsShowed()
    return self.captainTips ~= nil
end

function CaptainController:showCaptainTips(d)
    if cc.isDead(self.captainTips) then
        self.captainTips = CaptainTips.new()
        self.captainTips:setLocalZOrder(1000)
        self:addChild(self.captainTips)
    end
    self.captainTips:show()
    self.captainTips:refresh(d)
    self:getTouchMask():show()
end

function CaptainController:hideCaptainTips(cancel)
    if self.captainTips and cc.isDead(self.captainTips) == false then
        self.captainTips:cancel(cancel)
        self.captainTips:hide()
        self:getTouchMask():hide()
        self.captainTips:removeFromParent()
        self.captainTips = nil
    end
end

function CaptainController:showObtainView(resstr, resourcefrom, cname)
    local obt = CaptainObtainView.new()
    self:addChild(obt)
    obt:show()
    --[[ local arr = string.split(resstr, ";")

    local ress = {}
    for k, v in ipairs(arr) do
        local arrr = string.split(v, "|")
        if arrr[1] and arrr[2] then
            table.insert(ress, arrr)
        end
    end ]]
    local arr = string.split(resourcefrom, "|")
    if not arr[1] or not arr[2] then 
        display.pushToast(L("sourceTips1"))
        return
    end

    local ress = string.splitTwice(GD:getConvertResource(resstr, tonumber(arr[1]), tonumber(arr[2])), {";", "|"})
    for _,v in ipairs(ress) do
        if v[3] then
            v[3] = string.split(v[3], "#")
        end
    end
    obt:refresh(ress, cname)
end

function CaptainController:gotoFeature(data) --功能跳转
    display.resourceGotoFeature(data)
    self:closeCollectView()
    self:closeCaptainView()
end

function CaptainController:initCollectors()
    self.hCollectors = {}
    local cs = GD:getCaptainCollectors()
    for k, v in pairs(cs) do
        self.hCollectors[checknumber(v.ID)] = v
    end
end

function CaptainController:initLocations()
    self.hLocations = {}
    local ls = GD:getCaptainLocations()
    for k, v in pairs(ls) do
        self.hLocations[checknumber(v.ID)] = v
    end
end

function CaptainController:initTalks()
    self.hTalks = {}
    local ts = GD:getCaptainTalks()
    for k, v in pairs(ts) do
        self.hTalks[checknumber(v.ID)] = v
    end
end

function CaptainController:getActionConfig(id)
    return self.hTalks[id]
end

function CaptainController:getCollectionsBySize()
end

function CaptainController:getCollectionsByType(t)
    local ret = {}
    for k, v in pairs(self.hCollectors) do
        if checknumber(v.type) == checknumber(t) then
            table.insert(ret, v)
        end
    end
    return ret
end

function CaptainController:getCollectionsByBagType(bt)
    local ret = {}
    for k, v in pairs(self.hCollectors) do
        if checknumber(v.bagType) == bt then
            ret[v.type] = ret[v.type] or {type=v.type}
            table.insert(ret[v.type], v)
        end
    end

    local sret = {}
    for k, v in pairs(ret) do
        table.sort(v, function(a, b)
            local ared = app:sendMsg("CaptainModelRedPoint", "getCollectorRedPoint", checknumber(a.ID))
            local bred = app:sendMsg("CaptainModelRedPoint", "getCollectorRedPoint", checknumber(b.ID))
            if ared ~= bred then
                return ared == true
            end

            if self.capModel then
                if (self.capModel:hasCollect(checknumber(a.ID)) ~= false) ~= (self.capModel:hasCollect(checknumber(b.ID)) ~= false) then
                    return self.capModel:hasCollect(checknumber(a.ID)) ~= false
                end
            end

            if checknumber(a.quality) == checknumber(b.quality) then
                return checknumber(a.ID) > checknumber(b.ID)
            else
                return checknumber(a.quality) > checknumber(b.quality)
            end
        end)
        table.insert(sret, v)
    end
    table.sort(sret, function(a, b)
        return checknumber(a.type) < checknumber(b.type)
    end)
    return sret
end

function CaptainController:getLocationsByType(t)
    local ret = {}
    for k, v in pairs(self.hLocations) do
        if v.type == t then
            table.insert(ret, v)
        end
    end
    return ret
end

function CaptainController:getRoomData()
    return self.capModel
end

function CaptainController:hasCollector(cid)
    if self.myModel then
        return self.myModel:localHasCollect(cid)
    end
    
    return false
end

CaptainController.RoomDataChange = "captain.room.datachange"
function CaptainController:reqRoomData(rid)
    -- print(debug.traceback())
    app.session:request("pb_captainRoom.C2S_VisitOtherCaptainRoom",{otherUid = rid},function(msg)
        if msg.ok then
            if self.capModel == nil or self.capModel:getCaptainID() ~= rid then
                self.capModel = CaptainModel.new(rid)
            end

            self.capModel:read(msg.data)

            if rid == UD.uid then
                self.myModel = self.capModel
            end
            EM:notify(CaptainController.RoomDataChange)
        end
	end)
end

function CaptainController:reqSetLocation(lid, cid)
    local currentID = checknumber(self.capModel:getCurrentCollectInLocation(lid))
    local collectLocation = self.capModel:collectLocation(cid)
    local arg = {location={{ID=lid, Furniture=cid}}}
    if collectLocation ~= 0 then
        arg = {
            location = {
                {ID=lid, Furniture=0},
                {ID=collectLocation, Furniture=0},
                {ID=collectLocation, Furniture=currentID},
                {ID=lid, Furniture=cid},
            }
        }
    end
    app.session:request("pb_captainRoom.C2S_UpdateCaptainRoom", arg, function(msg)
        self.capModel:resetLocationConfigs(msg.location)
        EM:notify(CaptainController.RoomDataChange)
	end)
end

function CaptainController:reqPraise(id)
    app.session:request("pb_captainRoom.C2S_PraiseOtherCaptainRoom",{otherUid = id},function(msg)
        if msg.ok then
            display.pushToast(L("captain_praise_success"))
            self.capModel:resetServerData(msg.serData)
            EM:notify(CaptainController.RoomDataChange)
        end
	end)
end

function CaptainController:reqSetRoomConfig(cfg)
    app.session:request("pb_captainRoom.C2S_EditMessageBoardConfig",{MsgConfig = cfg},function(msg)
        if msg.ok == false then
            display.pushToast(L("captain_set_config_fail"))
        else
            self.capModel:resetMessageConfig(msg.MsgConfig)
            EM:notify(CaptainController.RoomDataChange)
        end
	end)
end

CaptainController.MessageListChange = "captain.message.listchange"

-- function CaptainController:getMessageList()
--     local messages = {}
--     for i, v in pairs(self.capModel.messageList) do
--         table.insert(messages, v)
--     end

--     table.sort(messages, function(a, b)
--         return a.Stamp > b.Stamp
--     end)

--     return messages
-- end

function CaptainController:leaveMessage(tid, message)
    app.session:request("pb_captainRoom.C2S_LeaveMessage",{otherUid = tid, Value = message},function(msg)
        if msg and msg.ok then
            if self.capModel:getCaptainID() == tid then
                -- self.capModel.messageList = msg.MessageData
                self.capModel:resetMessages(msg.MessageData)
                EM:notify(CaptainController.MessageListChange)
            end
        end
	end)
end

function CaptainController:reqMessage(tid)
    app.session:request("pb_captainRoom.C2S_QueryCaptainRoomServerData",{uid = tid},function(msg)
        if self.capModel:getCaptainID() == tid then
            self.capModel:resetServerData(msg.serData)
            EM:notify(CaptainController.MessageListChange)
            EM:notify(CaptainController.RoomDataChange)
        end
	end)
end

-- CaptainController.VisitCountsChange = "captain.visit.countschange"
-- function CaptainController:reqCounts(tid)
--     app.session:request("pb_captainRoom.C2S_RefreshVisitData",{},function(msg)
--         EM:notify(CaptainController.VisitCountsChange, msg.NewVisitedNum, msg.NewPraisedNum)
-- 	end)
-- end

function CaptainController:reqSetString(str, color, board, frame)
    local p = {
        Value = str,
        Color = color,
        BoardType = board,
        FrameType = frame,
    }
    app.session:request("pb_captainRoom.C2S_EditRoomString",{pars=p},function(msg)
        if msg.ok then
            self.capModel:resetStringConfig(msg.pars)
            EM:notify(CaptainController.RoomDataChange)
        end
    end)
end

function CaptainController:checkString(t, cb)
    if app:isNeedCheckInput() then
        app:checkInput(t, function(response,errorMsg,code)
            -- dump(response, "response:")
            if code == 200 then
                if response and response.result then
                    t = response.result
                    cb( t )
                end
            else
                display.pushToast(L("network_error"))
            end
        end, true)
    else
        cb( t )
    end
end

return CaptainController